<?php
Yii::import('application.widgets.chart.AbstractPieChart');

class LoanAmountRangeChart extends AbstractPieChart{

	public $title='Loans by Amount';

	protected function getData(){
		$commandBuilder= Yii::app()->db->getSchema()->getCommandBuilder();
		$maxAmount=$this->getMaxAmount();
		$topAmount=$this->getTopAmount($maxAmount);
		$step=$topAmount/10;

		$criteria=new CDbCriteria();
		$criteria->select='FLOOR(amount/'.$step.') as amountRange, count(*) as count';
		$criteria->group='amountRange';

		$command=$commandBuilder->createFindCommand(Loan::model()->getTableSchema(),$criteria);
		$row=$command->queryAll();
		$result=array();
		foreach ($row as $teamRow){
			$result[]=array('value'=>intval($teamRow['count']),'name'=>sprintf('%s - %s',$teamRow['amountRange']*$step,($teamRow['amountRange']+1)*$step));
		}
		return $result;
	}

	private function getMaxAmount(){
		$commandBuilder= Yii::app()->db->getSchema()->getCommandBuilder();
		$criteria=new CDbCriteria();
		$criteria->select='max(amount) as maxAmount';
		$command=$commandBuilder->createFindCommand(Loan::model()->getTableSchema(),$criteria);
		$row=$command->queryRow();
		return $row['maxAmount'];
	}

	private function getTopAmount($maxAmount){
		$topAmount=$maxAmount;
		$digits=0;
		while($topAmount>10){
			$digits++;
			$topAmount=intval($topAmount/10);
		}
		if($topAmount<2){
			$topAmount=2;
		}
		return ($topAmount)*pow(10, $digits);
	}
}